﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Adams.Admin.Presentation.Controllers
{
    [Authorize]
    [EnsureSsl]
    public class FilesController : Controller
    {
        [AppendLayoutViewModel]
        public ActionResult Index()
        {

            var model = Business.Files.Index.PageLoad();
            ViewBag.Message = Request["msg"];
            return View(model);
        }

        public JsonResult GridLoad(DataTransfer.GridLoadInput gridinput)
        {
            var model = Business.Files.Index.GridLoad(gridinput);
            return Json(model);
        }

        [AppendLayoutViewModel]
        public ActionResult Create(int id)
        {
            var model = Business.Files.Create.PageLoad(id);
            return View(model);
        }

        public JsonResult Save(Adams.Admin.DataTransfer.Files.Create.FormInput input)
        {
            var model = Business.Files.Create.Save(input);
            return Json(model);
        }

        public FileContentResult View(int id)
        {
            var model = Business.Files.Index.GetFile(id);
            return File(model.Content, model.ContentType);
        }

        public FileContentResult Download(int id)
        {
            var model = Business.Files.Index.GetFile(id);
            var sections = model.Url.Split('/');
            var filename = sections[sections.Length - 1];
            return File(model.Content, model.ContentType, filename);
        }

        public RedirectResult Delete(int id)
        {
            Business.Files.Index.Delete(id);
            var model = new { Deleted = true };
            return Redirect("/Files?msg=2");
        }

        public JsonResult Upload(string qqfile)
        {
            System.IO.Stream filestream = Request.InputStream;
            int length = Convert.ToInt32(filestream.Length);
            string contenttype = Shared.IOHelper.GetContentTypeByFileExtension(qqfile);
            string extension = Shared.IOHelper.GetFileExtension(qqfile);
            byte[] filebytes = new byte[length];
            int readposition = filestream.Read(filebytes, 0, length);

            var uploadedfile = new Adams.Admin.DataTransfer.Files.Index.UploadedFile() { 
                Content = filebytes,
                Size = length,
                ContentType = contenttype,
                Name = qqfile,
                Extension = extension
            };

            Business.Files.Index.Upload(uploadedfile);

            return Json(new { success = true });
        }
    }
}
